import {
  getNewCartGoods,
  mergeLocalCart,
  findCartList,
  insertCartApi,
  deleteCartApi,
  updateCartApi,
  checkAllCartApi,
} from "@/api/cart";

//购物车模块
export default {
  namespaced: true,
  actions: {
    //加入购物车
    insertCart({ rootState, commit }, payload) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          //已经登陆
          insertCartApi({ skuId: payload.skuId, count: payload.count })
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              commit("setCart", data.result);
              resolve();
            });
        } else {
          //未登陆
          commit("insertCart", payload);
          resolve();
        }
      });
    },
    //获取最新的商品信息
    findCart({ rootState, commit, state }) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          //已经登陆
          findCartList().then((data) => {
            commit("setCart", data.result);
          });
          resolve();
        } else {
          //未登陆
          //同时发送所有商品的请求（购物车有几件商品就发几个请求） 等所有请求成功，一并修改本地购物车的数据
          //Pormise.all(promise的数组).then(data => {})
          const promiseArr = state.list.map((item) => {
            return getNewCartGoods(item.skuId);
          });
          Promise.all(promiseArr).then((dataList) => {
            dataList.forEach((item, index) => {
              commit("updateCart", {
                skuId: state.list[index].skuId,
                ...item.result,
              });
            });
            resolve();
          });
        }
      });
    },
    // 删除购物车商品
    deleteCart({ commit, rootState }, skuId) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          //已经登陆

          deleteCartApi([skuId])
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              commit("setCart", data.result);
              resolve();
            });
        } else {
          //未登陆
          commit("deleteCart", skuId);
          resolve();
        }
      });
    },
    //修改购物车的 数量 以及选中状态
    updateCart({ commit, rootState }, payload) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          //已经登陆
          updateCartApi(payload)
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              commit("setCart", data.result);
            });
        } else {
          //未登陆
          commit("updateCart", payload);
          resolve();
        }
      });
    },
    //全选状态的修改
    checkAllCart({ commit, rootState, getters }, selected) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 已经登陆
          const ids = getters.validList.map((item) => item.skuId);
          checkAllCartApi({ selected, ids })
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              commit("setCart", data.result);
              resolve();
            });
        } else {
          //未登陆
          getters.validList.forEach((item) => {
            commit("updateCart", { skuId: item.skuId, selected });
          });
        }
      });
    },
    //批量删除 以及清空失效商品
    batchDeleteCart({ rootState, commit, getters }, isClear) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          //已经登陆
          const skuIdArr = getters[
            isClear ? "invalidList" : "selectedList"
          ].map((item) => {
            return item.skuId;
          });
          deleteCartApi(skuIdArr)
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              commit("setCart", data.result);
            });
        } else {
          //未登陆
          getters[isClear ? "invalidList" : "selectedList"].forEach((item) => {
            commit("deleteCart", item.skuId);
          });
        }
      });
    },
    //购物车中修改sku规格的方法
    updateCartSku({ rootState, state, commit }, { oldSkuId, newSkuId }) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          //已经登陆
          const oldGoods = state.list.find(
            (item) => item.skuId === oldSkuId
          );
          deleteCartApi([oldSkuId])
            .then(() => {
              return insertCartApi({ skuId: newSkuId.skuId, count: oldGoods.count });
            })
            .then(() => {
              return findCartList();
            })
            .then((data) => {
              commit("setCart", data.result);
              resolve();
            });
        } else {
          //未登陆
          //1.找出旧的sku信息
          const oldGoods = state.list.find((item) => {
            return item.skuId === oldSkuId;
          });
          //2.删除
          commit("deleteCart", oldSkuId);
          //3.新旧sku合并成一条新的商品
          const {
            skuId,
            price: nowPrice,
            inventory: stock,
            specsText: attrsText,
          } = newSkuId;
          const newGoods = { ...oldGoods, skuId, nowPrice, stock, attrsText };
          //4.添加商品
          commit("insertCart", newGoods);
          resolve();
        }
      });
    },
    //合并购物车
    async mergeLocalCart({ state, commit }, value) {
      //准备合并的参数
      const cartList = state.list.map((item) => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count,
        };
      });
      //调用合并参数的API接口
      await mergeLocalCart(cartList);

      //合并成功后 清空本地
      commit("setCart", []);
    },
  },

  // --------------------------------------------------------------------------------

  mutations: {
    //加入购物车
    insertCart(state, payload) {
      //约定的字段必须和服务端的一致
      //购物车的字段 id skuId name attrsText picture price nowPrice selected stock count isEffective
      //添加购物车的规则
      //1.有相同的商品： 查询其商品的数量进行累加 并把其加到最新的位置
      //2.没有相同的商品：直接保存在最新的位置
      const sameIndex = state.list.findIndex(
        (goods) => goods.skuId === payload.skuId
      );
      if (sameIndex != -1) {
        const count = state.list[sameIndex].count;
        payload.count += count;
        //删除原来的商品
        state.list.splice(sameIndex, 1);
        //添加新的商品
        state.list.unshift(payload);
      } else {
        state.list.unshift(payload);
      }
    },
    //根据商品的最新信息更新本地购物车列表
    updateCart(state, goods) {
      const updateGoods = state.list.find((item) => {
        return item.skuId == goods.skuId;
      });
      for (const key in goods) {
        if (
          goods[key] !== undefined &&
          goods[key] !== null &&
          goods[key] !== ""
        ) {
          updateGoods.key = goods[key];
          updateGoods[key] = goods[key];
        }
      }
    },
    // 删除购物车商品
    deleteCart(state, skuId) {
      const index = state.list.findIndex((item) => {
        return item.skuId == skuId;
      });
      state.list.splice(index, 1);
    },
    //设置购物车
    setCart(state, payload) {
      state.list = payload;
    },
  },

  // --------------------------------------------------------------------------------

  state: () => ({
    //购物车列表商品
    list: [],
  }),

  // --------------------------------------------------------------------------------

  getters: {
    //有效商品
    validList(state) {
      //库存stock大于0  商品有效标识isEffective 等于true
      return state.list.filter((goods) => goods.stock > 0 && goods.isEffective);
    },
    //有效商品总数量
    validTotal(state, getters) {
      return getters.validList.reduce((sum, item) => {
        return sum + item.count;
      }, 0);
    },
    //有效商品总金额
    validAmount(state, getters) {
      return (
        getters.validList.reduce((sum, item) => {
          return sum + item.count * item.nowPrice * 100;
        }, 0) / 100
      );
    },
    //无效商品数据的列表
    invalidList(state) {
      return state.list.filter((item) => {
        return item.stock <= 0 || item.isEffective === false;
      });
    },
    //已选商品的列表
    selectedList(state, getters) {
      return getters.validList.filter((item) => {
        return item.selected == true;
      });
    },
    //已选商品的总件数
    selectedTotal(state, getters) {
      return getters.selectedList.reduce((sum, item) => {
        return sum + item.count;
      }, 0);
    },
    //已选商品的总金额
    selectedAmount(state, getters) {
      return (
        getters.selectedList.reduce((sum, item) => {
          return sum + item.count * Math.round(item.nowPrice * 100);
        }, 0) / 100
      );
    },
    //是否全选
    isCheckAll(state, getters) {
      return (
        getters.validList.length === getters.selectedList.length &&
        getters.selectedList.length !== 0
      );
    },
  },
};
